<?php

namespace app\common\model;

use think\Model;
use think\Session;
use think\Validate;

/**
 * Created by PhpStorm.
 * Author: Masky
 * Date: 2017/11/1
 * Time: 16:20
 */
class GlobalData extends Model {
	
	const TYPE_STRING=0;
	const TYPE_ARRAY=1;
	
	public function addData($input){
		$validate=new Validate(['group'=>'require']);
		$result=FALSE;
		if($validate->check($input)){
			$group=$input['group'];
			unset($input['group']);
			foreach ($input as $key=>$item){
				if($this->get(['name'=>$key,'group'=>$group])){
					$this->save(['name'=>$key,'value'=>$item],['name'=>$key,'group'=>$group]);
				}else{
					$this->create(['name'=>$key,'value'=>$item,'group'=>$group,'created_at'=>time()]);
				}
			}
			
			$result =TRUE;
		}else{
			$this->error=$validate->getError();
		}
		return $result;
	}
	
	public function editData($input){
		$validate=new Validate(['group'=>'require']);
		$result=FALSE;
		if($validate->check($input)){
			$result=$this->save($input,['id'=>$input['id']]);
			$result || $this->error="编辑失败";
		}else{
			$this->error=$validate->getError();
		}
		return $result;
	}
	
	public function getInfo($condition=[],$field='*',$order='id desc'){
		
		$result=$this->where($condition)->field($field)->order($order)->find();
		$result && $this->formatSelect($result);
		return [$result['name']=>$result['value']];
	}
	
	public function formatSelect(&$data){
		$data['created_at_dis']=date("Y-m-d H:i:s",$data['created_at']);
	}
	public function getList($condition=[],$field='*',$order='id asc',$size=15){
		
		$result=$this->where($condition)->field($field)->order($order)->paginate($size,false,['query' =>input()]);
		$list=[];
		if($result){
			foreach ($result as &$item){
				$this->formatSelect($item);
				$list[$item['name']]=$item['value'];
			}
		}
		return $list;
	}
	
	public function deleteData($condition){
		$result=$this->where($condition)->select();
		if($result){
			foreach($result as $item){
				$this->where(['id'=>$item['id']])->delete();
			}
		}
		return TRUE;
	}
}